<script setup lang="ts">
import {computed, nextTick, onMounted, ref} from "vue";
import {useRoute} from "vue-router";
import {deleteDocumentById, getDocumentById, updateDocument} from "../../apis/DocumentApi.js";
import {elPrompt} from "../../utils/elPrompt.ts";
import {Keyword} from "../../interfaces/Keyword.ts";
import {Document} from "../../interfaces/Document.ts";
import {Result} from "../../interfaces/Result.ts";
import {FormRules} from "element-plus";
import router from "../../router/router.js";
import {useUserStore} from "../../stores/userStore.ts";
import showSize from '../../utils/showSize.js'

const document = ref<Document>({
  title: 'title',
  commentStatus: '开启',
  createTime: "",
  id: 0,
  isPublic: '私有',
  keywords: [],
  size: 0,
  status: "正常",
  updateTime: "",
  userId: 0
})
const keywords = ref<Keyword[]>()
const rules = ref<FormRules<typeof document>>({
  title: [
    {validator: validateTitle, trigger: 'blur'}
  ],
  keywords: [
    {validator: validateKeywords, trigger: 'blur'}
  ],
})

function validateTitle(rule: any, value: string, callback: any) {
  const rge = /^.*\.(doc|docx|xls|xlsx|ppt|pptx|pdf)$/
  if (!rge.test(value)) return callback(new Error('标题必须包含文件后缀，如：example.doc'))
  callback()
}

function validateKeywords(rule: any, value: Keyword[], callback: any) {
  if (!(value.length > 0)) return callback(new Error('至少需要一个关键词'))
  callback()
}

onMounted(() => {
  const documentId = parseInt(<string>useRoute().params.documentId)
  getDocumentById(documentId, (result: Result<Document>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    document.value = result.data
    keywords.value = document.value?.keywords
    formatKeyword()
  })
})

const keywordInputVisible = ref(false)
const keywordInput = ref('')
const keywordInputRef = ref()

function deleteKeyword(keyword: Keyword) {
  keywords.value = keywords.value?.filter((item: Keyword) => {
    if (item.id !== keyword.id) return item
  })
  formatKeyword()
  document.value.keywords = keywords.value
}

function addKeyword(keyword: string) {
  keywordInputVisible.value = false
  if (!keyword) return
  const index = keywords.value?.length
  keywords.value?.push(<Keyword>{
    id: index,
    value: keyword
  })
  keywordInput.value = ''
}

function formatKeyword() {
  keywords.value?.forEach((item: Keyword, index: number) => {
    keywords.value[index].id = index
  })
}

function showKeywordInput() {
  keywordInputVisible.value = true
  nextTick(() => {
    keywordInputRef.value!.input!.focus()
  })
}

const isPublic = computed(() => {
  return document.value.isPublic === '公开'
})

function save(document: Document) {
  updateDocument(document, (result:Result<any>) => {
    if (result.status !== 200) return elPrompt(result.message, "error")
    elPrompt('保存成功！', "success")
  })
}

const deleteDialogVisible = ref(false)

function deleteDocument(document: Document) {
  deleteDocumentById(document.id, (result:Result<any>) => {
    if (result.status !== 200) return elPrompt(result.message, 'error')
    elPrompt('删除成功', 'success')
    deleteDialogVisible.value = false
    router.push(`/document/user/${useUserStore().value.id}`)
  })
}
</script>

<template>
  <div class="form">
    <el-form
        ref="ruleFormRef"
        :model="document"
        status-icon
        :rules="rules"
    >
      <el-form-item prop="title">
        <div class="form-item">
          <span class="item-name">标题</span>
          <el-input v-model="document.title"/>
        </div>
      </el-form-item>
      <el-form-item prop="keywords">
        <div class="form-item">
          <div class="item-name">关键词</div>
          <div class="keywords">
            <el-tag v-for="keyword in keywords"
                    :key="keyword.id"
                    closable
                    :disable-transitions="false"
                    @close="deleteKeyword(keyword)"
            >
              {{ keyword.value }}
            </el-tag>
            <el-input
                v-if="keywordInputVisible"
                ref="keywordInputRef"
                v-model="keywordInput"
                size="small"
                @keyup.enter="addKeyword(keywordInput)"
                @blur="addKeyword(keywordInput)"
            />
            <el-button
                v-else
                size="small"
                @click="showKeywordInput">
              + 关键词
            </el-button>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="size">
        <div class="form-item">
          <span class="item-name">大小</span>
          <span>{{ showSize(document.size) }}</span>
        </div>
      </el-form-item>
      <el-form-item prop="status">
        <div class="form-item">
          <span class="item-name">状态</span>
          <span>
            <el-tag v-if="document.status === '正常'" type="success">{{ document.status }}</el-tag>
            <el-tag v-else type="danger">{{ document.status }}</el-tag>
          </span>
        </div>
      </el-form-item>
      <el-form-item prop="commentStatus">
        <div class="form-item">
          <span class="item-name">评论区状态</span>
          <span>
            <el-tag v-if="document.commentStatus === '开启'" type="success">{{ document.commentStatus }}</el-tag>
            <el-tag v-else type="danger">{{ document.commentStatus }}</el-tag>
          </span>
        </div>
      </el-form-item>
      <el-form-item prop="isPublic">
        <div class="form-item">
          <span class="item-name">是否公开</span>
          <span>
            <el-switch
                v-model="document.isPublic"
                active-text="公开"
                inactive-text="私有"
                active-value="公开"
                inactive-value="私有"
                style="--el-switch-on-color: var(--color-primary); --el-switch-off-color: var(--color-danger)"
            />
          </span>
          <el-text type="primary" v-show="isPublic">（公开文档任何人均可浏览与下载）</el-text>
          <el-text type="danger" v-show="!isPublic">（私有文档仅自己可浏览与下载）</el-text>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="form-item">
          <span class="item-name">操作</span>
          <span>
            <el-button type="primary" @click="save(document)">保存</el-button>
            <el-button type="danger" @click="deleteDialogVisible = true">删除</el-button>
          </span>
        </div>
      </el-form-item>
    </el-form>
  </div>
  <div class="dialog">
    <el-dialog
        v-model="deleteDialogVisible"
        title="删除文档"
        width="30%"
    >
      <span>确认删除{{ document.title }}?</span>
      <template #footer>
      <span class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="deleteDocument(document)">确认删除</el-button>
      </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="less">
.form {
  .form-item {
    display: flex;
    flex-direction: row;
    width: 100%;
    margin: 10px 0;

    .el-input {
      width: 90%;
    }

    .item-name {
      width: 75px;
    }

    .keywords {
      .el-tag {
        margin-right: 10px;
      }
    }
  }
}

</style>